package com.asiainfo.service;
/*
 * 
 * 卡操作service
 */
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import com.asiainfo.bean.Card;
import com.asiainfo.bean.VIP;
import com.asiainfo.dao.Card_Dao;

public class CardService {
	// 判断卡的有效性
	Logger logger = Logger.getLogger("");
	public boolean justcarduserable(Card card) {
		int time = (int) new Date().getTime();
		if (card.getDate() + card.getEffective() > time) {
			if (card.getType() == 1) {
				return true;
			} else if (card.getNum() > 0) {
				return true;
			}
		}
		return false;
	}
	//增加一张新卡
	public void addCard(String[] args) {
		VipService vs = new VipService();
		VIP vip = vs.findVipByName(args[1]);
		if (vip == null) {
			//添加卡的用户不存在
			logger.warning("对不起，您所指定的用户不存在");
			System.out.println("对不起，您所指定的用户不存在");
		} else {
			if (args[2].equals("年卡")) {
				//用户添加年卡
				if (args.length != 3) {
					logger.warning("对不起，请输入合法参数");
					System.out.println("对不起，请输入合法参数");
					return;
				}
				addYearCard(args[1], vip);
			} else {
				//用户添加次卡
				if (args.length != 4) {
					logger.warning("对不起，请输入合法参数");
					System.out.println("对不起，请输入合法参数");
					return;
				}
				addSecondCard(args[1], Integer.parseInt(args[3]), vip);
			}
		}
	}
	//为合法用户添加年卡
	public void addYearCard(String name, VIP vip) {
		Card_Dao card_dao = new Card_Dao();
		Card card = new Card(1, (int) new Date().getTime(), 0, 1, 365 * 24 * 60 * 60, vip.getId());
		int newid = card_dao.add(card);
		if (newid > 0) {
			System.out.println("OK.A new 年卡  added to " + vip.getName() + "(" + vip.getId() + ")");
		} else {
			logger.warning("对不起，卡绑定失败");
			System.out.println("对不起，卡绑定失败");
		}
	}
	//为合法用户添加次卡
	public void addSecondCard(String name, int num, VIP vip) {
		Card_Dao card_dao = new Card_Dao();
		Card card = new Card(2, (int) new Date().getTime(), num, 1, 3 * 365 * 24 * 60 * 60, vip.getId());
		int newid = card_dao.add(card);
		if (newid > 0) {
			System.out
					.println("OK.A new 次卡 with " + num + " times added to " + vip.getName() + "(" + vip.getId() + ")");
		} else {
			logger.warning("对不起，卡绑定失败");
			System.out.println("对不起，卡绑定失败");
		}
	}

	// 查询某用户所有已激活的卡
	public List<Card> findUsingCardsByVipId(int vip_id) {
		Card_Dao card_dao = new Card_Dao();
		List<Card> cards = card_dao.findUsingCardsByVipId(vip_id);
		return cards;
	}

	// 查询某用户所有未激活的卡
	public List<Card> findCardsByVipId(int vip_id) {
		Card_Dao card_dao = new Card_Dao();
		List<Card> cards = card_dao.findCardsByVipId(vip_id);
		return cards;
	}
	
	//根据卡编号查找卡
	public Card findCardById(int card_id){
		Card_Dao card_dao = new Card_Dao();
		return card_dao.findCardById(card_id);
	}
	//更新卡信息
	public void updatecard(Card card){
		Card_Dao card_dao = new Card_Dao();
		card_dao.update(card);
	}
}
